import { useState, useEffect, useMemo, useCallback } from 'react'

/**
 * 检测是否为移动端设备
 * 结合用户代理和屏幕宽度进行判断
 */
export function detectMobile(): boolean {
  if (typeof window === 'undefined') return false;
  
  const userAgent = navigator.userAgent.toLowerCase();
  const isMobileUA = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/.test(userAgent);
  const isMobileScreen = window.innerWidth <= 768;
  return isMobileUA || isMobileScreen;
}

/**
 * 自定义hook，判断是否为移动端设备
 * 优化版本：添加防抖和缓存机制
 * @returns {boolean} 是否为移动设备（屏幕宽度 <= 768px 或移动设备用户代理）
 */
export function useIsMobile() {
  // 缓存用户代理检测结果，避免重复计算
  const isMobileUA = useMemo(() => {
    if (typeof window === 'undefined') return false;
    const userAgent = navigator.userAgent.toLowerCase();
    return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/.test(userAgent);
  }, []);

  const [isMobile, setIsMobile] = useState(() => detectMobile())
  
  // 使用防抖优化resize事件
  const debouncedResize = useCallback(() => {
    let timeoutId: NodeJS.Timeout;
    
    const handleResize = () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        const isMobileScreen = window.innerWidth <= 768;
        setIsMobile(isMobileUA || isMobileScreen);
      }, 100); // 100ms防抖
    };
    
    return handleResize;
  }, [isMobileUA]);
  
  useEffect(() => {
    const resizeHandler = debouncedResize();
    window.addEventListener('resize', resizeHandler, { passive: true });
    return () => window.removeEventListener('resize', resizeHandler);
  }, [debouncedResize])
  
  return isMobile
}

export default useIsMobile
